package com.howie.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.howie.common.constant.ProductConstant;
import com.howie.common.to.SkuReductionTo;
import com.howie.common.to.SpuBoundsTo;
import com.howie.common.to.es.SkuEsModel;
import com.howie.common.utils.R;
import com.howie.gulimall.product.dao.SpuInfoDescDao;
import com.howie.gulimall.product.entity.*;
import com.howie.gulimall.product.feign.CouponFeignService;
import com.howie.gulimall.product.feign.SearchFeignService;
import com.howie.gulimall.product.feign.WareFeignService;
import com.howie.gulimall.product.service.*;
import com.howie.gulimall.product.vo.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.howie.common.utils.PageUtils;
import com.howie.common.utils.Query;

import com.howie.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {
    @Autowired
    private SpuInfoDescService spuInfoDescService; // 注入SpuInfoDescServiceImpl
    @Autowired
    private SpuImagesService spuImagesService; // 注入SpuImagesServiceImpl
    @Autowired
    private AttrService attrService;
    @Autowired
    private ProductAttrValueService productAttrValueService;
    @Autowired
    private SkuInfoService skuInfoService;
    @Autowired
    private SkuImagesService skuImagesService;
    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    private CouponFeignService couponFeignService;
    @Autowired
    private BrandService brandService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private WareFeignService wareFeignService; // 库存服务的远程客户端接口
    @Autowired
    private SearchFeignService searchFeignService; // es服务的远程客户端接口

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }
    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo spuSaveVo) {
        // 1、保存spu的基本信息(pms_spu_info)
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuSaveVo,spuInfoEntity);
        this.saveBaseSpuInfo(spuInfoEntity);

        // 2、保存spu的图片描述(pms_spu_info_desc)
        List<String> imageDesc = spuSaveVo.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescEntity.setDecript(StringUtils.join(imageDesc,","));
        spuInfoDescService.saveSpuInfoDesc(spuInfoDescEntity);

        // 3、保存spu的图片集(pms_spu_images)
        List<String> images = spuSaveVo.getImages();
        spuImagesService.saveImages(spuInfoEntity.getId(),images);

        // 4、保存spu的规格参数(pms_product_attr_value)
        List<BaseAttrs> baseAttrs = spuSaveVo.getBaseAttrs();
        List<ProductAttrValueEntity> productAttrValueEntities = baseAttrs.stream().map((item) -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            productAttrValueEntity.setSpuId(spuInfoEntity.getId());
            productAttrValueEntity.setAttrId(item.getAttrId());
            // 根据属性id查询属性名
            AttrEntity attrEntity = attrService.getById(item.getAttrId());
            productAttrValueEntity.setAttrName(attrEntity.getAttrName());

            productAttrValueEntity.setAttrValue(item.getAttrValues());
            productAttrValueEntity.setQuickShow(item.getShowDesc());
            return productAttrValueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveBatch(productAttrValueEntities);

        // 5、保存spu的积分信息(gulimall_sms -> sms_spu_bounds)
        Bounds bounds = spuSaveVo.getBounds();
        SpuBoundsTo spuBoundsTo = new SpuBoundsTo();
        BeanUtils.copyProperties(bounds,spuBoundsTo);
        spuBoundsTo.setSpuId(spuInfoEntity.getId());
        R r = couponFeignService.saveSpuBounds(spuBoundsTo);
        if(r.getCode() != 0){
            log.error("远程服务保存spu积分信息失败！");
        }

        // 6、保存当前spu对应所有sku信息
        List<Skus> skus = spuSaveVo.getSkus();
        if(skus != null && skus.size() > 0){
            skus.forEach((sku) ->{
                String defaultImg = "";
                for(Images img : sku.getImages()){
                    if(img.getDefaultImg() == 1){
                        defaultImg = img.getImgUrl();
                    }
                }
                // 6.1、sku的基本信息(pms_sku_info)
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(sku,skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setSkuDefaultImg(defaultImg);

                skuInfoService.saveSkuInfo(skuInfoEntity);

                // 6.2、sku的基图片信息(pms_sku_images)
                List<SkuImagesEntity> imagesEntities = sku.getImages().stream().map((image) -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
                    skuImagesEntity.setImgUrl(image.getImgUrl());
                    skuImagesEntity.setDefaultImg(image.getDefaultImg());

                    return skuImagesEntity;
                }).filter(entity ->{
                    // 返回true就是需要，返回false就是剔除
                    return StringUtils.isNotEmpty(entity.getImgUrl());
                }).collect(Collectors.toList());
                // TODO 没有图片路径的无需保存
                skuImagesService.saveBatch(imagesEntities);

                // 6.3、sku的销售信息(pms_sku_sale_attr_value)
                List<Attr> attrs = sku.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attrs.stream().map((attr -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(attr, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuInfoEntity.getSkuId());

                    return skuSaleAttrValueEntity;
                })).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);

                // 6.4、sku的优惠、满减等信息(gulimall_sms -> sms_sku_ladder/sms_sku_full_reduction/sms_member_price)
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(sku,skuReductionTo);
                skuReductionTo.setSkuId(skuInfoEntity.getSkuId());
                if(skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(BigDecimal.ZERO) > 0){
                    R r1 = couponFeignService.saveSkuReduction(skuReductionTo);
                    if(r1.getCode() != 0){
                        log.error("远程服务保存sku优惠信息失败！");
                    }
                }
            });
        }
    }

    @Override
    public void saveBaseSpuInfo(SpuInfoEntity spuInfoEntity) {
        this.baseMapper.insert(spuInfoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
        // 动态构造查询条件
        // 1、检索关键字 key。这里 key 可能是商品id/商品名
        String key = (String) params.get("key");
        if(StringUtils.isNotEmpty(key)){
            wrapper.and(queryWrapper -> {
                queryWrapper.eq("id",key).or().like("spu_name",key);
            });
        }
        // 2、检索三级分类(通过分类id)
        String catelogId = (String) params.get("catelogId");
        if(StringUtils.isNotEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)){
            wrapper.eq("catalog_id",catelogId);
        }
        // 3、检索品牌id
        String brandId = (String) params.get("brandId");
        if(StringUtils.isNotEmpty(brandId) && !"0".equalsIgnoreCase(brandId)){
            wrapper.eq("brand_id",brandId);
        }
        // 4、检索商品状态
        String status = (String) params.get("status");
        if(StringUtils.isNotEmpty(status)){
            wrapper.eq("publish_status",status);
        }
        IPage<SpuInfoEntity> page = this.page(new Query<SpuInfoEntity>().getPage(params), wrapper);
        return new PageUtils(page);
    }

    @Override
    public void up(Long spuId) {
        // 1、组装es需要的数据(to: SkuEsModel)
        // TODO: 查询当前sku的所有可以用来被检索的规格属性
        List<ProductAttrValueEntity> attrValueEntities = productAttrValueService.getListForSpu(spuId);
        // 通过spuId查询出所有的attrId
        List<Long> attrIds = attrValueEntities.stream().map(ProductAttrValueEntity::getAttrId).collect(Collectors.toList());
        // 可检索的attrId
        List<Long> enableSearchAttrIds = attrService.getEnableSearchAttrIds(attrIds);

        Set<Long> idSet = new HashSet<>(enableSearchAttrIds);
        // 包含可检索attr属性的ProductAttrValueEntity，再进行映射为SkuEsModel.Attrs
        List<SkuEsModel.Attrs> skuEsModelAttrs = attrValueEntities.stream().filter(item -> {
            return idSet.contains(item.getAttrId());
        }).map(productAttrValueEntity -> {
            SkuEsModel.Attrs attrs = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(productAttrValueEntity,attrs);
            return attrs;
        }).collect(Collectors.toList());

        // 1.1、查出当前spuId对应的所有sku信息，品牌的名字。
        List<SkuInfoEntity> skuInfoEntities = skuInfoService.getSkuInfosBySpuId(spuId);

        // 聚合skuId
        List<Long> skuIds = skuInfoEntities.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());

        // TODO: 需要向库存服务发送请求，检验对应的skuId商品是否有库存
        Map<Long, Boolean> stockMap = null;
        try{
            R skuHasStock = wareFeignService.getSkuHasStock(skuIds); // 调用远程服务，获取库存信息
            TypeReference<List<SkuHasStockVo>> typeReference = new TypeReference<List<SkuHasStockVo>>(){};
            List<SkuHasStockVo> data = skuHasStock.getData(typeReference);

            // 将封装有库存信息集合data转为map。将skuId设置为key，将hasStock设置为value
            stockMap = data.stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, SkuHasStockVo::getHasStock));
        } catch(Exception e){
            log.error("调用远程服务ware-gulimall出现了问题，原因：{}",e);
        }

        Map<Long, Boolean> finalStockMap = stockMap;
        List<SkuEsModel> upSkuEsModels = skuInfoEntities.stream().map(sku -> {
            SkuEsModel skuEsModel = new SkuEsModel();
            BeanUtils.copyProperties(sku,skuEsModel);
            /*
            需要单独设置的属性：
            skuPrice/skuImg/hasStock/hotScore/brandName/brandImg/catalogName/attrs
            */
            skuEsModel.setSkuPrice(sku.getPrice()); // skuPrice
            skuEsModel.setSkuImg(sku.getSkuDefaultImg()); // skuImg
            if(finalStockMap == null){
                skuEsModel.setHasStock(true); // 调用远程服务出现问题时，就设置为true(默认有库存)
            }else{
                skuEsModel.setHasStock(finalStockMap.get(sku.getSkuId())); // hasStock
            }
            // TODO: 热度评分 0
            skuEsModel.setHotScore(0L);
            // TODO: 品牌和分类的信息
            BrandEntity brandEntity = brandService.getById(sku.getBrandId());
            skuEsModel.setBrandName(brandEntity.getName()); // brandName
            skuEsModel.setBrandImg(brandEntity.getLogo()); // brandImg
            CategoryEntity categoryEntity = categoryService.getById(sku.getCatalogId());
            skuEsModel.setCatalogName(categoryEntity.getName()); // catalogName

            skuEsModel.setAttrs(skuEsModelAttrs); // attrs
            return skuEsModel;
        }).collect(Collectors.toList());

        // 2、将数据发送给es进行保存(gulimall-search)，调用远程服务
        R result = searchFeignService.productStatusUp(upSkuEsModels);
        if(result.getCode() == 0){
            // 调用成功
            // TODO: 修改spu的当前状态(已上架)
            this.baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
        }else{
            // 调用失败
            // TODO: 这里有个坑！重复调用？接口幂等性。重试机制
        }
    }
}